<?php

/**
 * BusiInfo
 * 
 * @author xuxuwei-
 * @version 
 */


class Base_BusiInfo {
	
	protected $logger;
	
	public function __construct(array $options = null, array $convertRule = null)
	{
		$this->logger = Zend_Registry::get("logger");	
		
		if (is_array($options)) {
			$this->setOptions($options, $convertRule);
		}
		
	}
   
	public function __set($name, $value)
	{
		$names = $this->formatMethodName($name);
		$this->logger->debug(__FUNCTION__. print_r($names,true));
		if (sizeof($names) == 1) {		
			$method = 'set_' . $names[0];
			if (('mapper' == $name) || !method_exists($this, $method)) {
				//throw new Exception('Invalid property');
				//donothing
				return;
			}
			$this->$method($value);
		} else {
			$this->__get($names[0])->__set( $name[1]);
		}
	}
   
	public function __get($name)
	{
		$names = $this->formatMethodName($name);
		$method = 'get_' . $names[0];
		
		if (('mapper' == $names[0]) || !method_exists($this, $method)) {
			//throw new Exception('Invalid property');
			//donothing
			return;
		}
		if (sizeof($names) == 1) {
			return $this->$method();
		} else {
			return $this->$method()->__get($names[1]);
		}
	}
	
	public function setOptions(array $options, array $convertRule = null)
	{
		$methods = get_class_methods($this);
		foreach ($options as $key => $value) {
			if(is_array($convertRule) && array_key_exists($key, $convertRule)) {
				//$this->logger->debug($key);
				$key = $convertRule[$key];
				//$this->logger->debug($key);
			}
			$method = '__set';
			
			$this->$method($key, $value);
		}
		return $this;
	}
	
	private function formatMethodName($name) {
		$pos = strpos($name, '.');
		if($pos == false) {
			$rtn[0] = $name;
		} else {
			$rtn[0] = substr($name, 0, $pos);
			$rtn[1] = substr($name, $pos + 1);
		}
		
		
		//convert abc_def to abcDef
		$method = '';
		$tmp = explode('_', $rtn[0]);
		
		foreach ($tmp as $key=>$value) {
			if ($key == 0 ) {
				$method = $method . $value;
			} else {
				$method = $method . ucfirst($value);
			}
		}
		$rtn[0] = $method;
		return $rtn;
	}
	
	protected function getLogger() {
		if ($this->logger == null) {
			$this->logger = Zend_Registry::get("logger");
		}
		return $this->logger;
	}
 
}

